import { Form, Input,Icon, Pagination, Button } from "antd";
import React from "react";
import styles from "../../index.less"
import FieldTag from "./fieldTag";
import { formFieldList } from "@/services/formInteraction";
import knowledgeHome from "@/services/knowledgeHome";

class StartNode extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      questionList:[],
      fieldList:[],
      focusIndex:-3,
      minIndex:0,
			maxIndex:10,
      current:1,
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initForm = data => {
    this.getFieldsList()
    let obj = {label:data.label}
    if(data.data){
      obj.basicQuestion = data.data.start.basicQuestion
      this.setState({
        questionList:data.data.start.questionList ? data.data.start.questionList : []
      })
    }
    this.props.form.setFieldsValue(obj)
  }

  getFieldsList = async () => {
    const { formId } = this.props
    const res = await formFieldList({formId})
    this.setState({
      fieldList:res
    })
  }

  setFieldIndex = index => {
    console.log(index);
    this.setState({
      focusIndex:index
    })
  }

  addFieldName = (tag,flag) => {
    let inputValue = this.props.form.getFieldValue(flag)
    inputValue = inputValue ?  inputValue + '<'+tag+'>' : '<'+tag+'>'
    let obj = {}
    obj[flag] = inputValue
    this.props.form.setFieldsValue(obj)
  }

  addQuestion = () => {
    const { questionList } = this.state;
    const value = this.props.form.getFieldValue("question")
    if(value.length > 0){
      questionList.push(value)
      knowledgeHome.postFormFlowSimilarAdd()
      this.setState({
        questionList
      },() => {
        this.props.form.setFieldsValue({question:''})
      })
    }
  }

  onChangeInput = (e,i) => {
    const { questionList } = this.state;
    questionList[i] = e.target.value;
    this.setState({
      questionList
    })
  }

  delInput = (q,i) => {
    let { questionList,current,minIndex, maxIndex } = this.state;
    questionList.splice(i, 1);
    const questionPages = questionList.filter((item, index) => (index > minIndex || index === minIndex) && index < maxIndex);
    if (questionPages.length === 0 && current != 1) {
      current -= 1;
    }
    this.setState({
      questionList
    },() => {
      this.onChangeQuestionPage(current)
    })
  }

  upInput = (q,i) => {
    const { questionList } = this.state;
    questionList.splice(i, 1);
    questionList.unshift(q);
    knowledgeHome.postFormFlowSimilarDel()
    this.setState({
      questionList
    });
  }

  addFieldNameByIndex = (tag,i) => {
    const { questionList } = this.state;
    questionList[i] = questionList[i] ? questionList[i] + '<'+tag+'>' : '<'+tag+'>'
    this.setState({
      questionList
    })
  }

  onChangeQuestionPage = (current) => {
		const minIndex = (current - 1) * 10;
		const maxIndex = (current - 1) * 10 + 10;
		console.log(minIndex, maxIndex);
		this.setState({
			minIndex,
			maxIndex,
			current,
		});
	};

  checkSave = () => {
    let { questionList } = this.state;
    this.props.form.validateFields((error,values) => {
      if(!error){
        questionList = questionList.filter(item => item != undefined && item != '')
        let obj = {
          label:values.label,
          data:{
            start:{
              basicQuestion:values.basicQuestion,
              questionList
            }
          }
        }
        this.props.doSave(obj)
      }
    })
  }

  render(){
    const { focusIndex,fieldList,questionList,minIndex,maxIndex,current } = this.state;
    const { form:{getFieldDecorator} } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    return (
      <Form {...formItemLayout}>
        <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />基本信息</div>
        <Form.Item label="节点名称">
          {
            getFieldDecorator("label",{rules:[{required:true,message:"请输入"}]})(
              <Input className={styles.inputItem} maxLength={200} />
            )
          }
        </Form.Item>
        <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />自定义触发相似问</div>
        <Form.Item label="标准问">
          {
            getFieldDecorator("basicQuestion",{rules:[{required:true,message:"请输入"}]})(
              <Input onFocus={() => this.setFieldIndex(-1)} className={styles.inputItem} maxLength={200} />
            )
          }
          {
            focusIndex == -1 ? (
              <FieldTag fieldList={fieldList} click={(tag) => this.addFieldName(tag,'basicQuestion')} />
            ) : ''
          }
        </Form.Item>
        <Form.Item label="相似问">
          {
            getFieldDecorator("question")(
              <Input 
                onFocus={() => this.setFieldIndex(-2)} 
                className={styles.inputItem} 
                placeholder="请输入相似问题, 点击回车继续添加" 
                style={{width:"80%"}}
                onPressEnter={this.addQuestion}
                maxLength={200}
              />
            )
          }
          <Icon
            type='plus-circle'
            style={{
              fontSize: 20,
              marginLeft: 10,
              cursor: "pointer",
              marginTop: 5,
            }}
            onClick={this.addQuestion}
          />
          {
            focusIndex == -2 ? (
              <FieldTag fieldList={fieldList} click={(tag) => this.addFieldName(tag,'question')} />
            ) : ''
          }
        </Form.Item>
        {
          questionList.map((q,i) => {
            if ((i > minIndex || i === minIndex) && i < maxIndex) {
              return (
                <Form.Item key={i} label=" " colon={false}>
                  <Input 
                    value={q}
                    style={{ width: "80%" }}
                    className={styles.inputItem}
                    onFocus={(e) => this.setFieldIndex(i)}
                    onChange={(event) => { this.onChangeInput(event, i); }}
                    maxLength={200}
                  />
                  <Icon
                    className='dynamic-delete-button'
                    type='close-circle'
                    style={{
                      fontSize: 20,
                      marginLeft: 10,
                      cursor: "pointer",
                      marginTop: 5,
                    }}
                    onClick={() => this.delInput(q, i)}
                  />
                  <Icon
                    type='arrow-up'
                    style={{
                      fontSize: 20,
                      marginLeft: 10,
                      cursor: "pointer",
                      marginTop: 5,
                    }}
                    onClick={() => this.upInput(q, i,)}
                  />
                  {
                    focusIndex == i ? (
                      <FieldTag fieldList={fieldList} click={(tag) => this.addFieldNameByIndex(tag,i)} />
                    ) : ''
                  }
                </Form.Item>
              )
            }
          })
        }
        {
          questionList.length > 10 ? (
            <Form.Item label=" " colon={false} style={{textAlign:"center"}}>
              <Pagination 
                total={questionList.length}
                current={current}
                size={10}
                onChange={this.onChangeQuestionPage}
              />
            </Form.Item>
          ) : ''
        }
        <Form.Item label=" " colon={false} >
          <Button type="primary" onClick={this.checkSave}>保存</Button>
        </Form.Item>
      </Form>
    )
  }
}

export default Form.create()(StartNode)